package api.json.demo003.config;

import apijson.Log;
import apijson.framework.APIJSONApplication;
import apijson.framework.APIJSONCreator;
import apijson.orm.FunctionParser;
import apijson.orm.SQLConfig;
import apijson.orm.SQLExecutor;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@Configuration
public class ApiJsonConfig implements CommandLineRunner {

    @Value("${spring.datasource.db-name}")
    private String dbName;

    @Value("${spring.datasource.db-version}")
    private String dbVersion;

    @Autowired
    private ApplicationContext applicationContext;

    public static ApplicationContext APPLICATION_CONTEXT;
    public static String DB_NAME;
    public static String DB_VERSION;

    @PostConstruct
    public void init() {
        APPLICATION_CONTEXT = applicationContext;
        DB_NAME = dbName;
        DB_VERSION = dbVersion;
    }

    static {
        APIJSONApplication.DEFAULT_APIJSON_CREATOR = new APIJSONCreator<Long>() {
            @Override
            public SQLConfig createSQLConfig() {
                return new DBSQLConfig();
            }

            @Override
            public SQLExecutor createSQLExecutor() {
                return new DBSQLExecutor();
            }

            @Override
            public FunctionParser createFunctionParser() {
                return new MySQLFunctionParser();
            }
        };
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public DataSource dataSource() {
        return new HikariDataSource();
    }

    @Override
    public void run(String... args) throws Exception {
        Log.DEBUG = false;
        APIJSONApplication.init(true);
    }

}
